<?php
// +----------------------------------------------------------------------
// | RXThinkCMF_EVTP5.1_PRO前后端分离旗舰版框架 [ RXThinkCMF ]
// +----------------------------------------------------------------------
// | 版权所有 2018~2021 南京RXThinkCMF研发中心
// +----------------------------------------------------------------------
// | 官方网站: http://www.rxthink.cn
// +----------------------------------------------------------------------
// | 作者: 牧羊人 <rxthinkcmf@163.com>
// +----------------------------------------------------------------------
// | 免责声明:
// | 本软件框架禁止任何单位和个人用于任何违法、侵害他人合法利益等恶意的行为，禁止用于任何违
// | 反我国法律法规的一切平台研发，任何单位和个人使用本软件框架用于产品研发而产生的任何意外
// | 、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、附带
// | 或衍生的损失等)，本团队不承担任何法律责任。本软件框架只能用于公司和个人内部的法律所允
// | 许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

namespace app\admin\service;


use app\admin\model\Channel;
use app\admin\model\ChannelApply;
use app\admin\model\Game;
use app\admin\model\BoxGame;
use app\admin\model\RoleMenuPlat;
use app\admin\model\UserPlat;
use app\admin\model\UserPlatGame;
use app\admin\model\UserRolePlat;
use app\channel\model\UserChannel;
use app\models\ForumNewMarketGiftItem;
use think\Db;
use think\Exception;
use Yii;

/**
 * 后台渠道用户管理-服务类
 * @author ZhangXuanNeng
 * @since: 2023/08/22
 * Class UserPlatService
 * @package app\admin\service
 */
class UserPlatService extends BaseService
{
    /**
     * 构造函数
     * LevelService constructor.
     */
    public function __construct()
    {
        $this->model = new UserPlat();
    }

    /**
     * 获取数据列表
     * @return array
     * @since 2023/08/22
     * @author ZhangXuanNeng
     */
    public function getList()
    {
        $param = request()->param();
        // 查询条件
        $map = [];
//        $map[] = ['level', '=', 1];
        // 用户账号
        $username = getter($param, "username");
        if ($username) $map[] = ["username", 'like', "%{$username}%"];
        // 用户姓名
        $realname = getter($param, "realname");
        if ($realname) $map[] = ['realname', 'like', "%{$realname}%"];
        if (!empty($param['id'])) $map[] = ['id', '=', $param['id']];
        $nickname = getter($param, "nickname");
        if (!empty($param['nickname'])) $map[] = ['nickname', 'like', "%{$nickname}%"];
        //时间
        if (!empty($param['create_time'])) {
            $map[] = ['create_time', '>=', $param['create_time'][0]];
            $map[] = ['create_time', '<=', $param['create_time'][1]];
        }
//        $list = $this->model->where($map)->order("id DESC")->page(PAGE, PERPAGE)->select();
//        $count = $this->model->where($map)->count();
//        if (!empty($list)){
//            $userIdList = array_column($list->toArray(), "id");
//            //获取用户对应的角色
//            $userRolePlatModel = new UserRolePlat();
//            $roleInfo = $userRolePlatModel->alias("ur")
//                ->field(['ur.user_id', 'r.id', 'r.name'])
//                ->join(DB_PREFIX . 'role_plat r', 'ur.role_id=r.id')
//                ->distinct(true)
//                ->where('ur.user_id', 'in', $userIdList)
//                ->where('r.status', '=', 1)
//                ->order('r.sort asc')
//                ->select()->toArray();
//            $userRoleInfo = array();
//            if (!empty($roleInfo)){
//                foreach ($roleInfo as $roleItem){
//                    $userRoleInfo[$roleItem['user_id']][] = array("id"=>$roleItem['id'], "name"=>$roleItem['name']);
//                }
//            }
//            foreach ($list as &$item){
//                if (isset($userRoleInfo[$item['id']])){
//                    if ($item['avatar']) $item['avatar'] = get_image_url($item['avatar']);
//                    $item['roles'] = $userRoleInfo[$item['id']];
//                }
//            }
//        }
//        $result = message("操作成功", true, $list);
//        $result['count'] = $count;
//        return $result;

        return parent::getList($map);
    }

    /**
     * 添加或编辑
     * @return mixed
     * @throws \think\db\exception\BindParamException
     * @throws \think\exception\PDOException
     * @since 2020/11/19
     * @author 牧羊人
     */
    public function edit()
    {
        // 请求参数
        $data = request()->param();
        // 用户名
        $username = trim($data['username']);
        // 密码
        $password = trim($data['password']);
        // 添加时设置密码
        if (empty($data['id'])) {
            $data['create_time'] = time();
            $data['password'] = get_password($password . $username);
            // 用户名重复性验证
            $count = $this->model
                ->where("username", '=', $username)
                ->where("mark", "=", 1)
                ->count();
            if ($count > 0) {
                return message("系统中已存在相同的用户名", false);
            }
        } else {
            $data['update_time'] = time();
            // 用户名重复性验证
            $count = $this->model
                ->where("username", '=', $username)
                ->where("id", "<>", $data['id'])
                ->where("mark", "=", 1)
                ->count();
            if ($count > 0) {
                return message("系统中已存在相同的用户名", false);
            }

            if (empty($password)) {
                unset($data['password']);
            } else {
                $data['password'] = get_password($password . $username);
            }
        }

        // 头像处理
//        $avatar = getter($data, 'avatar');
//        if (empty($avatar)) {
//            return message('请上传头像之后再提交...', false);
//        }
//
//        if (strpos($avatar, "temp")) {
//            $data['avatar'] = save_image($avatar, 'user');
//        } else {
//            $data['avatar'] = str_replace(IMG_URL, "", $data['avatar']);
//        }

        $error = "";
        $result = $this->model->edit($data, $error);
        if (!$result) {
            return message($error, false);
        }

        // 删除用户整体缓存
        $this->model->cacheDAll();

        // 删除已存在的用户角色关系数据
        $userRoleService = new UserRolePlatService();
        $userRoleService->deleteUserRole($result);
        // 插入用户角色关系数据
        $userRoleService->insertUserRole($result, $data['role_ids']);
        return message();
    }

    /**
     * 获取用户信息
     * @param $userId
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @since 2020/11/19
     * @author 牧羊人
     */
    public function getUserInfo($userId)
    {
        $userInfo = $this->model->getInfo($userId);

        // 返回参数
        $result = array();
        $result['id'] = $userInfo['id'];
        $result['avatar'] = $userInfo['avatar'];
        $result['realname'] = $userInfo['realname'];
        $result['nickname'] = $userInfo['nickname'];
        $result['gender'] = $userInfo['gender'];
        $result['mobile'] = $userInfo['mobile'];
        $result['email'] = $userInfo['email'];
        $result['address'] = $userInfo['address'];
        $result['intro'] = $userInfo['intro'];
        $result['roles'] = [];
        $result['authorities'] = [];

        // 权限节点列表
        $menuService = new MenuService();
        $permissionList = $menuService->getPermissionsList($userId);
        $result['permissionList'] = $permissionList;
        return message("操作成功", true, $result);
    }

    /**
     * 更新个人资料
     * @param $userId 用户ID
     * @return array
     * @throws \think\db\exception\BindParamException
     * @throws \think\exception\PDOException
     * @author 牧羊人
     * @since 2021/4/23
     */
    public function updateUserInfo($userId)
    {
        // 参数
        $param = request()->param();
        // 个人信息
        $data = [
            'id' => $userId,
            'realname' => $param['realname'],
            'nickname' => $param['nickname'],
            'gender' => $param['gender'],
            'mobile' => $param['mobile'],
            'email' => $param['email'],
            'intro' => $param['intro'],
        ];
        // 头像处理
        $avatar = isset($param['avatar']) ? $param['avatar'] : "";
        if (strpos($avatar, "data:image") !== false) {
            $expData = explode(';', $avatar);
            $fileInfo = explode('/', $expData[0]);
            $fileExt = $fileInfo[1] == 'jpeg' ? 'jpg' : $fileInfo[1];
            // 文件存储路径
            $filePath = create_image_path("user", $fileExt);

            // 获取图片流
            $item = explode(',', $avatar);
            file_put_contents(ATTACHMENT_PATH . $filePath, base64_decode($item[1]));

            $data['avatar'] = $filePath;
        } else {
            $data['avatar'] = str_replace(IMG_URL, "", $param['avatar']);
        }
        $result = $this->model->edit($data);
        if (!$result) {
            return message("更新资料信息失败", false);
        }
        return message("更新资料信息成功");
    }

    /**
     * 修改密码
     * @param $userId 用户ID
     * @return mixed
     * @throws \think\db\exception\BindParamException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @since 2020/11/19
     * @author 牧羊人
     */
    public function updatePwd($userId)
    {
        // 获取参数
        $param = request()->param();
        // 原始密码
        $oldPassword = trim(getter($param, "oldPassword"));
        if (!$oldPassword) {
            return message("旧密码不能为空", false);
        }
        // 新密码
        $newPassword = trim(getter($param, "newPassword"));
        if (!$newPassword) {
            return message("新密码不能为空", false);
        }
        $userInfo = $this->model->getInfo($userId);
        if (!$userInfo) {
            return message("用户信息不存在", false);
        }
        if ($userInfo['password'] != get_password($oldPassword . $userInfo['username'])) {
            return message("旧密码输入不正确", false);
        }
        $item = [
            'id' => $userId,
            'password' => get_password($newPassword . $userInfo['username']),
        ];
        $result = $this->model->edit($item);
        if (!$result) {
            return message("修改失败", false);
        }
        return message("修改成功");
    }

    /**
     * 重置密码
     * @return mixed
     * @throws \think\db\exception\BindParamException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @author 牧羊人
     * @since 2020/11/19
     */
    public function resetPwd()
    {
        // 获取参数
        $param = request()->param();
        // 用户ID
        $userId = getter($param, "id");
        if (!$userId) {
            return message("用户ID不能为空", false);
        }
        $userInfo = $this->model->getInfo($userId);
        if (!$userInfo) {
            return message("用户信息不存在", false);
        }
        $item = [
            'id' => $param['id'],
            'password' => get_password("123456" . $userInfo['username']),
        ];
        $result = $this->model->edit($item);
        if (!$result) {
            return message("重置密码失败", false);
        }
        return message("重置密码成功");
    }

    public function repack()
    {
        $param = request()->param();
        $map = [];
        $map[] = ['mark', '=', 1];
        if (!empty($param['id'])) $map[] = ['id', '=', $param['id']];
        $getList = $this->model->where($map)->select();
        if ($getList) {
            foreach ($getList as $value) {
                $this->model->update(['package_status' => 0], ['id' => $value['id']]);
            }
            return message("打包成功", true);
        }
    }

    /**
     * 用户游戏列表
     */
    public function userPlatGames()
    {
        // 请求参数
        $param = request()->param();
        $required_fields = ['plat_id'];
        foreach ($required_fields as $field) {
            if (!isset($param[$field])) {
                return message("缺少 '$field' 参数！", false);
            }
        }

        $gameList = BoxGame::field(['id as game_id', 'game_name'])->order("id DESC")->select()->toArray();
        $platGameList = UserPlatGame::field("game_id")
            ->where("plat_id", '=', $param['plat_id'])
            ->select()
            ->toArray();
        $platGameList = array_key_value($platGameList, "game_id");
        foreach ($gameList as &$val) {
            if (in_array($val['game_id'], $platGameList)) {
                $val['checked'] = true;
                $userPlatData = UserPlatGame::field("id")->where("game_id", '=', $val['game_id'])->where('plat_id', $param['plat_id'])->find();
                $val['id'] = $userPlatData['id'];
            }
        }
        return message("操作成功", true, $gameList);
    }


    /**
     * 分配游戏
     */
    public function saveUserPlatGame()
    {
        Db::startTrans();
        try {
            // 请求参数
            $param = request()->param();
            $required_fields = ['plat_id', 'plat_games'];
            foreach ($required_fields as $field) {
                if (!isset($param[$field])) {
                    return message("缺少 '$field' 参数！", false);
                }
            }

            $platGameArr = UserPlatGame::field(['id', 'plat_id', 'game_id'])->where('plat_id', $param['plat_id'])->select()->toArray();
            $platGameList = array_column($platGameArr, 'id');

            foreach ($param['plat_games'] as $item) {

                if (empty($item['id'])) {
                    $platModel = new UserPlatGame();
                    $platModel->plat_id = $param['plat_id'];
                    $platModel->game_id = $item['game_id'];
                    $platModel->create_time = date("Y-m-d H:i:s");
                    $platModel->save();
                } else {
//                unset($platGameList[$item['id']]);
                    $platGameList = array_diff($platGameList, [$item['id']]);
                }
            }


            //在user_channel表的game_id添加分配的游戏
            $platGameString = implode(',', array_column($param['plat_games'], 'game_id'));
            $userChannel = UserChannel::get($param['plat_id']);
            $userChannel->game_id = $platGameString;
            $userChannel->save();

            if (!empty($platGameList)) {
                //删除多余
                $deleteArr = array();
                foreach ($platGameList as $deleteItem) {
                    $deleteArr[] = $deleteItem;
                }
                UserPlatGame::whereIn('id', $deleteArr)->delete();
            }
            Db::commit();
            return message("编辑成功", true);
        } catch (Exception $e) {
            Db::rollback();
            return message($e->getMessage(), false);
        }
    }

    /**
     * 用户游戏列表
     */
    public function userApplyList()
    {
        // 请求参数
        $param = request()->param();
        $required_fields = ['plat_id'];
        foreach ($required_fields as $field) {
            if (!isset($param[$field])) {
                return message("缺少 '$field' 参数！", false);
            }
        }

        $gameList = Game::field(['id as game_id', 'game_name'])->order("id DESC")->select()->toArray();
        $platGameList = ChannelApply::field("game_id")
            ->where("channel_user_id", '=', $param['plat_id'])
            ->select()
            ->toArray();
        $platGameList = array_key_value($platGameList, "game_id");
        foreach ($gameList as &$val) {
            if (in_array($val['game_id'], $platGameList)) {
                $val['checked'] = true;
                $userPlatData = ChannelApply::field("id")->where("game_id", '=', $val['game_id'])->where('channel_user_id', $param['plat_id'])->find();
                $val['id'] = $userPlatData['id'];
            }
        }
        return message("操作成功", true, $gameList);
    }


    /**
     * 分配游戏
     */
    public function saveUserApply()
    {
        Db::startTrans();
        try {
            // 请求参数
            $param = request()->param();
            $required_fields = ['plat_id', 'plat_games'];
            foreach ($required_fields as $field) {
                if (!isset($param[$field])) {
                    return message("缺少 '$field' 参数！", false);
                }
            }

            $platGameArr = ChannelApply::field(['id', 'channel_user_id', 'game_id'])->where('channel_user_id', $param['plat_id'])->select()->toArray();
            $platGameList = array_column($platGameArr, 'id');

            foreach ($param['plat_games'] as $item) {

                if (empty($item['id'])) {
                    $platModel = new ChannelApply();
                    $platModel->channel_user_id = $param['plat_id'];
                    $platModel->game_id = $item['game_id'];
                    $platModel->save();
                } else {
                    $platGameList = array_diff($platGameList, [$item['id']]);
                }
            }

            if (!empty($platGameList)) {
                //删除多余
                $deleteArr = array();
                foreach ($platGameList as $deleteItem) {
                    $deleteArr[] = $deleteItem;
                }
                ChannelApply::whereIn('id', $deleteArr)->delete();
            }
            Db::commit();
            return message("编辑成功", true);
        } catch (Exception $e) {
            Db::rollback();
            return message($e->getMessage(), false);
        }
    }
}